<template>
  <div>
    <div>
      <input
          type="text"
          v-model="note"
          placeholder="输入备注"
          @keyup.enter="() => focusNext(hoursRef)"
      />
      <input
          type="number"
          v-model.number="hours"
          placeholder="时"
          ref="hoursRef"
          @keyup.enter="() => focusNext(minutesRef)"
      />
      <input
          type="number"
          v-model.number="minutes"
          placeholder="分"
          ref="minutesRef"
          @keyup.enter="() => focusNext(secondsRef)"
      />
      <input
          type="number"
          v-model.number="seconds"
          placeholder="秒"
          ref="secondsRef"
          @keyup.enter="startCountdown"
      />
      <button @click="startCountdown">开始倒计时</button>
    </div>

    <div v-if="timeLeft >= 0">
      剩余时间：{{ formatTime(timeLeft) }}
    </div>
    <div v-else>
      时间到！备注：{{ note }}
    </div>
  </div>
</template>

<script>
import { ref, nextTick } from 'vue';

export default {
  setup() {
    const note = ref('');
    const hours = ref(0);
    const minutes = ref(0);
    const seconds = ref(0);
    const timeLeft = ref(0);
    const hoursRef = ref(null);
    const minutesRef = ref(null);
    const secondsRef = ref(null);

    const focusNext = (nextRef) => {
      nextTick(() => {
        nextRef.value.focus();
      });
    };

    const formatTime = (time) => {
      const h = Math.floor(time / 3600);
      const m = Math.floor((time % 3600) / 60);
      const s = time % 60;
      return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    };

    const startCountdown = () => {
      timeLeft.value = hours.value * 3600 + minutes.value * 60 + seconds.value;
      updateCountdown();
    };

    const playBeepSound = () => {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const oscillator = audioContext.createOscillator();
      oscillator.type = 'square';
      oscillator.frequency.setValueAtTime(1000, audioContext.currentTime); // 1000 Hz frequency
      oscillator.connect(audioContext.destination);
      oscillator.start();
      oscillator.stop(audioContext.currentTime + 0.2); // Beep for 200 ms
    };

    let intervalId = null;
    const updateCountdown = () => {
      clearInterval(intervalId);
      intervalId = setInterval(() => {
        if (timeLeft.value > 0) {
          timeLeft.value--;
        } else {
          clearInterval(intervalId);
          playBeepSound(); // Play beep sound when countdown finishes
        }
      }, 1000);
    };

    return {
      note,
      hours,
      minutes,
      seconds,
      timeLeft,
      formatTime,
      startCountdown,
      focusNext,
      playBeepSound,
      hoursRef,
      minutesRef,
      secondsRef,
    };
  },
};
</script>
